package com.yiwyn.springbean.utils;

import com.yiwyn.springbean.context.SpringContext;
import com.yiwyn.springbean.service.DeptService;
import com.yiwyn.springbean.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class BizBeanUtil {


    private final Map<Class<?>, Object> beanCache = new HashMap<>();

    private final ApplicationContext applicationContext;

    private final String userId;


    public BizBeanUtil(String userId) {
        applicationContext = SpringContext.getApplicationContext();
        this.userId = userId;
    }

    public <T> T get(Class<T> clazz) {
        Object object = null;
        log.info("id:{} clazz:{}", userId, clazz);
        if (clazz.isAssignableFrom(UserService.User.class)) {
            UserService bean = applicationContext.getBean(UserService.class);
            object = bean.getUser(userId);
        } else if (clazz.isAssignableFrom(DeptService.Dept.class)) {
            DeptService bean = applicationContext.getBean(DeptService.class);
            UserService.User user = get(UserService.User.class);
            object = bean.dept(user.getDeptId());
        }
        return clazz.cast(object);
    }

    public <T> T getCache(Class<T> clazz) {
        Object object = null;
        if (beanCache.containsKey(clazz)) {
            return clazz.cast(beanCache.get(clazz));
        }
        log.info("id:{} clazz:{}", userId, clazz);
        if (clazz.isAssignableFrom(UserService.User.class)) {
            UserService bean = applicationContext.getBean(UserService.class);
            object = bean.getUser(userId);
        } else if (clazz.isAssignableFrom(DeptService.Dept.class)) {
            DeptService bean = applicationContext.getBean(DeptService.class);
            UserService.User user = getCache(UserService.User.class);
            object = bean.dept(user.getDeptId());
        }
        beanCache.put(clazz, object);
        return clazz.cast(object);
    }

}
